const { User, Scam, Comment } = require('../models');
const { Op } = require('sequelize');

// 获取用户列表
exports.getUsers = async (req, res) => {
  try {
    const { page = 1, limit = 10, search = '' } = req.query;
    const offset = (page - 1) * limit;

    const where = {};
    if (search) {
      where[Op.or] = [
        { username: { [Op.like]: `%${search}%` } },
        { email: { [Op.like]: `%${search}%` } }
      ];
    }

    const { count, rows } = await User.findAndCountAll({
      where,
      attributes: { exclude: ['password'] },
      order: [['createdAt', 'DESC']],
      limit: parseInt(limit),
      offset: parseInt(offset)
    });

    res.json({
      users: rows,
      total: count,
      currentPage: parseInt(page),
      totalPages: Math.ceil(count / limit)
    });
  } catch (error) {
    res.status(500).json({
      message: '获取用户列表失败',
      error: error.message
    });
  }
};

// 更新用户信息
exports.updateUser = async (req, res) => {
  try {
    const { id } = req.params;
    const { username, email, role } = req.body;

    const user = await User.findByPk(id);
    if (!user) {
      return res.status(404).json({
        message: '用户不存在'
      });
    }

    await user.update({
      username,
      email,
      role
    });

    res.json({
      message: '更新成功',
      user: {
        id: user.id,
        username: user.username,
        email: user.email,
        role: user.role
      }
    });
  } catch (error) {
    res.status(500).json({
      message: '更新失败',
      error: error.message
    });
  }
};

// 删除用户
exports.deleteUser = async (req, res) => {
  try {
    const user = await User.findByPk(req.params.id);
    if (!user) {
      return res.status(404).json({
        message: '用户不存在'
      });
    }

    await user.destroy();

    res.json({
      message: '删除成功'
    });
  } catch (error) {
    res.status(500).json({
      message: '删除失败',
      error: error.message
    });
  }
};

// 获取统计数据
exports.getStats = async (req, res) => {
  try {
    const [
      totalUsers,
      totalScams,
      totalComments,
      pendingScams,
      recentScams,
      recentUsers
    ] = await Promise.all([
      User.count(),
      Scam.count(),
      Comment.count(),
      Scam.count({ where: { status: 'pending' } }),
      Scam.findAll({
        include: [{ model: User, as: 'author', attributes: ['username'] }],
        order: [['createdAt', 'DESC']],
        limit: 5
      }),
      User.findAll({
        attributes: ['id', 'username', 'email', 'role', 'createdAt'],
        order: [['createdAt', 'DESC']],
        limit: 5
      })
    ]);

    res.json({
      stats: {
        totalUsers,
        totalScams,
        totalComments,
        pendingScams
      },
      recentScams,
      recentUsers
    });
  } catch (error) {
    res.status(500).json({
      message: '获取统计数据失败',
      error: error.message
    });
  }
};

// 获取内容列表
exports.getScams = async (req, res) => {
  try {
    const { page = 1, limit = 10, search = '', status = '' } = req.query;
    const offset = (page - 1) * limit;

    const where = {};
    if (search) {
      where[Op.or] = [
        { title: { [Op.like]: `%${search}%` } },
        { phone: { [Op.like]: `%${search}%` } }
      ];
    }
    if (status) {
      where.status = status;
    }

    const { count, rows } = await Scam.findAndCountAll({
      where,
      include: [{ model: User, as: 'author', attributes: ['username'] }],
      order: [['createdAt', 'DESC']],
      limit: parseInt(limit),
      offset: parseInt(offset)
    });

    res.json({
      scams: rows,
      total: count,
      currentPage: parseInt(page),
      totalPages: Math.ceil(count / limit)
    });
  } catch (error) {
    res.status(500).json({
      message: '获取内容列表失败',
      error: error.message
    });
  }
};

// 审核通过内容
exports.verifyScam = async (req, res) => {
  try {
    const scam = await Scam.findByPk(req.params.id);
    if (!scam) {
      return res.status(404).json({
        message: '内容不存在'
      });
    }

    await scam.update({ status: 'verified' });

    res.json({
      message: '审核通过成功'
    });
  } catch (error) {
    res.status(500).json({
      message: '审核失败',
      error: error.message
    });
  }
};

// 拒绝内容
exports.rejectScam = async (req, res) => {
  try {
    const scam = await Scam.findByPk(req.params.id);
    if (!scam) {
      return res.status(404).json({
        message: '内容不存在'
      });
    }

    await scam.update({ status: 'rejected' });

    res.json({
      message: '已拒绝'
    });
  } catch (error) {
    res.status(500).json({
      message: '操作失败',
      error: error.message
    });
  }
};

// 删除内容
exports.deleteScam = async (req, res) => {
  try {
    const scam = await Scam.findByPk(req.params.id);
    if (!scam) {
      return res.status(404).json({
        message: '内容不存在'
      });
    }

    await scam.destroy();

    res.json({
      message: '删除成功'
    });
  } catch (error) {
    res.status(500).json({
      message: '删除失败',
      error: error.message
    });
  }
}; 